<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>JavaWeb学习笔记 | Jixer的小屋</title><meta name="author" content="Jixer"><meta name="copyright" content="Jixer"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="JDBC介绍：java用来连接和操作数据库 注意：最后千万别忘掉关闭资源 快速上手前提需要导入mysql jar包 1234567891011121314151617181920212223242526import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;public class JDB">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaWeb学习笔记">
<meta property="og:url" content="http://www.lijunxi.site/posts/2996697887/index.html">
<meta property="og:site_name" content="Jixer的小屋">
<meta property="og:description" content="JDBC介绍：java用来连接和操作数据库 注意：最后千万别忘掉关闭资源 快速上手前提需要导入mysql jar包 1234567891011121314151617181920212223242526import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;public class JDB">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://q1.qlogo.cn/g?b=qq&nk=2770063826&s=640">
<meta property="article:published_time" content="2024-01-17T05:55:27.000Z">
<meta property="article:modified_time" content="2024-05-07T03:10:23.205Z">
<meta property="article:author" content="Jixer">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://q1.qlogo.cn/g?b=qq&nk=2770063826&s=640"><link rel="shortcut icon" href="/img/logo/favicon.ico"><link rel="canonical" href="http://www.lijunxi.site/posts/2996697887/index.html"><link rel="preconnect"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css?v=4.13.0"><link rel="stylesheet" href="/pluginsSrc/@fortawesome/fontawesome-free/css/all.min.css?v=6.5.1"><link rel="stylesheet" href="/pluginsSrc/@fancyapps/ui/dist/fancybox/fancybox.css?v=5.0.33" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: '/pluginsSrc/@egjs/infinitegrid/dist/infinitegrid.min.js?v=4.11.1',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JavaWeb学习笔记',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-05-07 11:10:23'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><link rel="stylesheet" href="/css/custom-all-min.css"><link rel="stylesheet" href="/css/custom-fancybox-min.css"><link rel="stylesheet" href="/css/custom-share-min.css"><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="" data-original="https://q1.qlogo.cn/g?b=qq&amp;nk=2770063826&amp;s=640" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">52</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">19</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="Jixer的小屋"><span class="site-name">Jixer的小屋</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">JavaWeb学习笔记</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-01-17T05:55:27.000Z" title="发表于 2024-01-17 13:55:27">2024-01-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-05-07T03:10:23.205Z" title="更新于 2024-05-07 11:10:23">2024-05-07</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>15分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JavaWeb学习笔记"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="JDBC"><a href="#JDBC" class="headerlink" title="JDBC"></a>JDBC</h2><p>介绍：java用来连接和操作数据库</p>
<p><strong>注意：最后千万别忘掉关闭资源</strong></p>
<h3 id="快速上手"><a href="#快速上手" class="headerlink" title="快速上手"></a>快速上手</h3><p>前提需要导入mysql jar包</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">import java.sql.Connection;</span><br><span class="line">import java.sql.DriverManager;</span><br><span class="line">import java.sql.Statement;</span><br><span class="line"></span><br><span class="line">public class JDBCDemo &#123;</span><br><span class="line">    public static void main(String[] args) throws Exception&#123;</span><br><span class="line">//        注册驱动</span><br><span class="line">        Class.forName(&quot;com.mysql.jdbc.Driver&quot;);</span><br><span class="line">//        获取链接</span><br><span class="line">//        useServerPrepStmts=true开启预编译功能</span><br><span class="line">        String url = &quot;jdbc:mysql://127.0.0.1:3306/test?useSSL=false&amp;useServerPrepStmts=true&quot;;</span><br><span class="line">        String username = &quot;root&quot;;</span><br><span class="line">        String password = &quot;123456&quot;;</span><br><span class="line">        Connection conn = DriverManager.getConnection(url, username, password);</span><br><span class="line">//        执行语句</span><br><span class="line">        String sql = &quot;update jdbc_test set password = 12121 where username = 1&quot;;</span><br><span class="line">//        获取执行对象</span><br><span class="line">        Statement statement = conn.createStatement();</span><br><span class="line">//        返回影响行数</span><br><span class="line">        int count = statement.executeUpdate(sql);</span><br><span class="line">        System.out.println(count);</span><br><span class="line">//        释放资源</span><br><span class="line">        conn.close();</span><br><span class="line">        statement.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="API"><a href="#API" class="headerlink" title="API"></a>API</h3><h4 id="DriverManager"><a href="#DriverManager" class="headerlink" title="DriverManager"></a>DriverManager</h4><p>通过<code>DriverManager.getConnection(url, username, password)</code>来得到一个Connection对象，代表与数据库连接成功</p>
<h4 id="Connection"><a href="#Connection" class="headerlink" title="Connection"></a>Connection</h4><p>获取执行sql对象</p>
<ul>
<li>通过调用<code>createStatemen()</code>方法获取一个Statement对象</li>
<li>通过调用<code>prepareStatement()</code>方法获取一个PrepareStatement对象</li>
</ul>
<p>事务管理</p>
<ul>
<li>通过调用<code>setAutoCommit(false)</code>方法来来关闭自动提交事务</li>
<li>通过调用<code>sqlSession.commit()</code>方法来回滚事务</li>
<li>通过调用<code>rollback()</code>方法来回滚事务</li>
</ul>
<p>事务管理就是关闭自动提交事务过后，执行的语句中若出现错误就会立刻回滚事务，一个都不执行；若语句执行完后没有提交事务，他也会回滚事务；</p>
<h4 id="Statement"><a href="#Statement" class="headerlink" title="Statement"></a>Statement</h4><p>代表执行对象</p>
<ul>
<li>通过调用<code>executeUpdate(sql)</code>来对数据进行增删改，返回受影响的行数（int）</li>
<li>通过调用<code>executeQuery(sql)</code>来对数据进行查询,返回一个ResultSet对象</li>
</ul>
<h4 id="PreparedStatement"><a href="#PreparedStatement" class="headerlink" title="PreparedStatement"></a>PreparedStatement</h4><p>代表执行对象，可以防止sql注入</p>
<p>需要在sql语句中传参的位置用?占位符代替，调用setInt&#x2F;setString(出现的位置, 需要代替的字符或者数字)来替换?，这样做的原理是使敏感字符用\带转义，让它变为一个字符，不参与sql作用。</p>
<p>例如：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">String name = &quot;1&quot;;</span><br><span class="line">String pas = &quot;&#x27;or &#x27;1&#x27; =&#x27;1&quot;; // sql注入代码</span><br><span class="line"> String sql = &quot;select * from jdbc_test where username = &#x27;&quot;+name+&quot;&#x27; and password = &#x27;&quot;+pas+&quot;&#x27;&quot;;</span><br><span class="line">Statement statement = connection.createStatement();</span><br><span class="line">ResultSet resultSet = statement.executeQuery(sql);</span><br></pre></td></tr></table></figure>

<p>这样写的sql语句为<code>select * from jdbc_test where username = &#39;1&#39; and passwor</code>d &#x3D; ‘’or ‘1’ &#x3D;’1’，这样的sql语句一定为真，导致sql注入</p>
<p>改进过后代码</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String sql = &quot;select * from jdbc_test where username = ? and password = ?&quot;;</span><br><span class="line">PreparedStatement preparedStatement = connection.prepareStatement(sql);</span><br><span class="line">preparedStatement.setString(1, name);</span><br><span class="line">preparedStatement.setString(2, pas);</span><br></pre></td></tr></table></figure>

<p>这样的sql为<code>select * from jdbc_test where username = &#39;1&#39; and password = &#39;\&#39;or \&#39;1\&#39; =\&#39;1\&#39;</code>就不会出现sql注入问题</p>
<h4 id="ResultSet"><a href="#ResultSet" class="headerlink" title="ResultSet"></a>ResultSet</h4><p>主要有两个重要的方法</p>
<ul>
<li>调用<code>next()</code>来判断是否下一行数据是否存在</li>
<li>调用<code>getString(&quot;1&quot;)/getInt(&quot;id&quot;)</code>来输出改行数据的第1列或者列名为id的数据</li>
</ul>
<h2 id="Druid"><a href="#Druid" class="headerlink" title="Druid"></a>Druid</h2><p>druid使阿里巴巴开源的数据库连接池，可以进行多个用户连接，一开始就开了几个Connetion连接，用完并不会关闭而是返回连接池等待下一个用户；而不是用一个开一次连接，用完就关闭，导致浪费时间。</p>
<p>需要引入druid和mysql jar包</p>
<p>与jdbc不同的是这里需要一个Properties配置文件来配置数据库连接池信息</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">driverClassName=com.mysql.jdbc.Driver</span><br><span class="line">url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false&amp;useServerPrepStmts=true</span><br><span class="line">username=root</span><br><span class="line">password=123456</span><br><span class="line"># 初始化连接数量</span><br><span class="line">initialSize=5</span><br><span class="line"># 最大连接数</span><br><span class="line">maxActive=10</span><br><span class="line"># 最大等待时间</span><br><span class="line">maxWait=3000</span><br></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">// 加载配置文件</span><br><span class="line">Properties prop = new Properties();</span><br><span class="line">// System.out.println(System.getProperty(&quot;user.dir&quot;));  获取当前目录是src</span><br><span class="line">prop.load(new FileInputStream(&quot;jdbc_demo/src/druid.properties&quot;));</span><br></pre></td></tr></table></figure>

<p>调用<code>DruidDataSourceFactory.createDataSource(prop)</code>返回一个DataSource对象，这个DataSource可以调用<code>getConnection()</code>来获取数据库连接返回一个Connection对象，拿到这个对象后的操作方法与上面一样</p>
<h2 id="Mybaits"><a href="#Mybaits" class="headerlink" title="Mybaits"></a>Mybaits</h2><p>Mybats是JDBC框架，免除了几乎所有JDBC代码以及设置参数和获取结果集的工作</p>
<p><strong>注意：别忘记关闭SqlSession开启的资源</strong></p>
<h3 id="目录"><a href="#目录" class="headerlink" title="目录"></a>目录</h3><p><img src="" data-original="/../img/article/QQ%E5%9B%BE%E7%89%8720230106061547.png"></p>
<p>java下单UserMapper为接口文件，resource下的UserMapper为Mapper的xml文件（存放sql数据）。</p>
<h3 id="mybatis-config的配置"><a href="#mybatis-config的配置" class="headerlink" title="mybatis-config的配置"></a><strong>mybatis-config的配置</strong></h3><p>放在resources目录下</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;</span><br><span class="line">&lt;!DOCTYPE configuration</span><br><span class="line">        PUBLIC &quot;-//mybatis.org//DTD Config 3.0//EN&quot;</span><br><span class="line">        &quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;&gt;</span><br><span class="line">&lt;configuration&gt;</span><br><span class="line"></span><br><span class="line">&lt;!-- default为默认选取的数据库，这样写可以切换不同的数据库，对应environment的id--&gt;</span><br><span class="line">    &lt;environments default=&quot;development&quot;&gt;</span><br><span class="line">        &lt;environment id=&quot;development&quot;&gt;</span><br><span class="line">&lt;!-- 事务管理方式，采用JDBC--&gt;</span><br><span class="line">            &lt;transactionManager type=&quot;JDBC&quot;/&gt;</span><br><span class="line">&lt;!-- 数据库连接池--&gt;</span><br><span class="line">            &lt;dataSource type=&quot;POOLED&quot;&gt;</span><br><span class="line">&lt;!-- 数据库的连接信息--&gt;</span><br><span class="line">                &lt;property name=&quot;driver&quot; value=&quot;com.mysql.jdbc.Driver&quot;/&gt;</span><br><span class="line">                &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql:///test&quot;/&gt;</span><br><span class="line">                &lt;property name=&quot;username&quot; value=&quot;root&quot;/&gt;</span><br><span class="line">                &lt;property name=&quot;password&quot; value=&quot;123456&quot;/&gt;</span><br><span class="line">            &lt;/dataSource&gt;</span><br><span class="line">        &lt;/environment&gt;</span><br><span class="line">    &lt;/environments&gt;</span><br><span class="line">    &lt;mappers&gt;</span><br><span class="line">&lt;!-- 加载sql映射文件--&gt;</span><br><span class="line">&lt;!-- &lt;mapper resource=&quot;com/ljx/mapper/UserMapper.xml&quot;/&gt;--&gt;</span><br><span class="line"></span><br><span class="line">&lt;!-- mapper代理方式，扫包，若还有多个如BrandMapper,....不需要一个一个添加sql映射文件，--&gt;</span><br><span class="line">        &lt;package name=&quot;com.ljx.mapper&quot;/&gt;</span><br><span class="line">    &lt;/mappers&gt;</span><br><span class="line">&lt;/configuration&gt;</span><br></pre></td></tr></table></figure>

<p>加载配置文件，获取sqlSessionFactory对象</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">String resource = &quot;mybatis-config.xml&quot;;</span><br><span class="line">InputStream inputStream = Resources.getResourceAsStream(resource);</span><br><span class="line">SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);</span><br></pre></td></tr></table></figure>

<p>获取SqlSession对象，继承了Conntection的事务管理</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SqlSession sqlSession = sqlSessionFactory.openSession();</span><br></pre></td></tr></table></figure>

<p>获得UserMapper接口代理对象</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">UserMapper userMapper = sqlSession.getMapper(UserMapper.class);</span><br></pre></td></tr></table></figure>

<p>接着就可以调用UserMapper的接口了（例如）</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">List&lt;User&gt; users = userMapper.selectAll();</span><br></pre></td></tr></table></figure>

<p><strong>注意：除了查询，其他的增删改均需要事务提交</strong><code>sqlSession.commit();</code></p>
<h3 id="XXXMapper的配置"><a href="#XXXMapper的配置" class="headerlink" title="XXXMapper的配置"></a><strong>XXXMapper的配置</strong></h3><p>放在resources&#x2F;com&#x2F;ljx&#x2F;mapper目录下，与java里面的目录相对应</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper</span><br><span class="line">        PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span><br><span class="line">        &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;!--namespace命名空间：为mapper的全限名，为java目录下mapper接口的地址，用来对应mapper--&gt;</span><br><span class="line">&lt;!--resultType返回类型，com.ljx.pojo.User是User类的文件地址--&gt;</span><br><span class="line">&lt;mapper namespace=&quot;com.ljx.mapper.UserMapper&quot;&gt;&lt;/mapper&gt;</span><br></pre></td></tr></table></figure>

<h4 id="select标签"><a href="#select标签" class="headerlink" title="select标签"></a>select标签</h4><p>普通查找</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectAll&quot; resultType=&quot;com.ljx.pojo.User&quot;&gt;</span><br><span class="line">        select *</span><br><span class="line">        from tb_user;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<p>含有敏感字符查找</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"> &lt;!-- #&#123;&#125;占位符，会将其替换为?，为了防止sql注入，$&#123;&#125;占位符，拼接sql，会存在sql注入问题--&gt;</span><br><span class="line">&lt;!-- 如遇到特殊字符如：&lt;，则会报错，因为xml小于是一种开始的格式，需要处理</span><br><span class="line">        1.转移字符：&amp;lt;</span><br><span class="line">        2.CDATA区：&lt;![CDATA[ &lt; ]]&gt;，其中&lt;![CDATA[内容]]&gt;里可以写多个字符</span><br><span class="line">--&gt;</span><br><span class="line">    &lt;select id=&quot;selectId&quot; resultType=&quot;com.ljx.pojo.User&quot;&gt;</span><br><span class="line">        select *</span><br><span class="line">        from tb_user</span><br><span class="line">        where id &lt;![CDATA[ &lt; ]]&gt; #&#123;id&#125;;</span><br><span class="line">    &lt;/select&gt;</span><br></pre></td></tr></table></figure>

<p>多条件查询</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectMore&quot; resultType=&quot;com.ljx.pojo.User&quot;&gt;</span><br><span class="line">        select *</span><br><span class="line">        from tb_user</span><br><span class="line">        where id = #&#123;id&#125;</span><br><span class="line">           and gender = #&#123;gender&#125;;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<p>动态查询</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--动态条件查询sql--&gt;</span><br><span class="line">&lt;!-- 并不是所有的参数都需要传入--&gt;</span><br><span class="line">&lt;!-- if标签，存在问题：第一个if若不存在就会出错。--&gt;</span><br><span class="line">&lt;!-- 解决：1、添加 1=1  2、用where标签替换where语句，若条件存在就会自动去掉and--&gt;</span><br><span class="line">&lt;select id=&quot;selectNiu&quot; resultType=&quot;com.ljx.pojo.User&quot;&gt;</span><br><span class="line">    select * from tb_user</span><br><span class="line">    &lt;where&gt;</span><br><span class="line">        &lt;if test=&quot;username != null and username != &#x27;&#x27;&quot;&gt;and username = #&#123;username&#125;&lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;id != null&quot;&gt;and id = #&#123;id&#125;&lt;/if&gt;</span><br><span class="line">    &lt;/where&gt;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<p>单条件查询</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--单条件动态查询--&gt;</span><br><span class="line">&lt;!-- choose标签相当于switch，when标签相当于case，test里放的是条件--&gt;</span><br><span class="line">&lt;!-- otherwise相当于default，若没有满足的条件就执行这个语句，否则不执行--&gt;</span><br><span class="line">&lt;select id=&quot;selectDan&quot; resultType=&quot;com.ljx.pojo.User&quot;&gt;</span><br><span class="line">    select * from tb_user</span><br><span class="line">    where</span><br><span class="line">    &lt;choose&gt;</span><br><span class="line">        &lt;when test=&quot;username != null and username != &#x27;&#x27;&quot;&gt;username = #&#123;username&#125;&lt;/when&gt;</span><br><span class="line">        &lt;when test=&quot;id != null&quot;&gt;id = #&#123;id&#125;&lt;/when&gt;</span><br><span class="line">        &lt;otherwise&gt;1 = 1&lt;/otherwise&gt;</span><br><span class="line">        &lt;/choose&gt;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<h4 id="insert标签"><a href="#insert标签" class="headerlink" title="insert标签"></a>insert标签</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- useGeneratedKeys=&quot;true&quot; keyProperty=&quot;id&quot; 返回添加数据id--&gt;</span><br><span class="line">&lt;insert id=&quot;add&quot; useGeneratedKeys=&quot;true&quot; keyProperty=&quot;id&quot;&gt;</span><br><span class="line">    insert into tb_user (username, password, gender, addr)</span><br><span class="line">    values (#&#123;username&#125;, #&#123;password&#125;, #&#123;gender&#125;, #&#123;addr&#125;)</span><br><span class="line">&lt;/insert&gt;</span><br></pre></td></tr></table></figure>

<h4 id="updated标签"><a href="#updated标签" class="headerlink" title="updated标签"></a>updated标签</h4><p>普通修改</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;update id=&quot;updated&quot;&gt;</span><br><span class="line">    update tb_user</span><br><span class="line">    set username = #&#123;username&#125;,</span><br><span class="line">        password = #&#123;password&#125;,</span><br><span class="line">        gender = #&#123;gender&#125;,</span><br><span class="line">        addr = #&#123;addr&#125;</span><br><span class="line">    where id = #&#123;id&#125;</span><br><span class="line">&lt;/update&gt;</span><br></pre></td></tr></table></figure>

<p>动态修改</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;update id=&quot;updatedDong&quot;&gt;</span><br><span class="line">    update tb_user</span><br><span class="line">    &lt;set&gt;</span><br><span class="line">        &lt;if test=&quot;username != null and username != &#x27;&#x27;&quot;&gt;username = #&#123;username&#125;,&lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;password != null and password != &#x27;&#x27;&quot;&gt;password = #&#123;password&#125;,&lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;gender != null and gender != &#x27;&#x27;&quot;&gt;gender = #&#123;gender&#125;,&lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;addr != null and addr != &#x27;&#x27;&quot;&gt;addr = #&#123;addr&#125;&lt;/if&gt;</span><br><span class="line">    &lt;/set&gt;</span><br><span class="line">    where id = #&#123;id&#125;</span><br><span class="line">&lt;/update&gt;</span><br></pre></td></tr></table></figure>

<h4 id="delete标签"><a href="#delete标签" class="headerlink" title="delete标签"></a>delete标签</h4><p>普通删除</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;delete id=&quot;delete&quot;&gt;</span><br><span class="line">    delete from tb_user where id = #&#123;id&#125;</span><br><span class="line">&lt;/delete&gt;</span><br></pre></td></tr></table></figure>

<p>批量删除</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 用foreach循环遍历，因为一开始并不知道数组有多少长度--&gt;</span><br><span class="line">&lt;!-- mybatis默认将collection参数为array，只能为这个，若想改变产生名字，则必须在传参的时候用@Params注解改变默认名字--&gt;</span><br><span class="line">&lt;!-- 例如：void deleteFor(@Param(&quot;ids&quot;) int[] ids);--&gt;</span><br><span class="line">&lt;delete id=&quot;deleteFor&quot;&gt;</span><br><span class="line">    delete from tb_user where id in</span><br><span class="line">    &lt;foreach collection=&quot;array&quot; item=&quot;id&quot; separator=&quot;,&quot; open=&quot;(&quot; close=&quot;)&quot;&gt;</span><br><span class="line">        #&#123;id&#125;</span><br><span class="line">    &lt;/foreach&gt;</span><br><span class="line">&lt;/delete&gt;</span><br></pre></td></tr></table></figure>

<h3 id="注解方式"><a href="#注解方式" class="headerlink" title="注解方式"></a>注解方式</h3><p>用注解方式就不用写xml文件，极大的方便了开发，所以简单的sql语句用注解，复杂的sql语句用xml文件</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">@Select(&quot;select * from tb_user&quot;)</span><br><span class="line">List&lt;User&gt; userAll();</span><br></pre></td></tr></table></figure>

<h2 id="Servlet"><a href="#Servlet" class="headerlink" title="Servlet"></a>Servlet</h2><p>Servlet是Java web的核心</p>
<h3 id="快速入门"><a href="#快速入门" class="headerlink" title="快速入门"></a>快速入门</h3><p>需要重写Servlet api中的5个方法</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">import javax.servlet.*;</span><br><span class="line">import javax.servlet.annotation.WebServlet;</span><br><span class="line">import java.io.IOException;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">@WebServlet(&quot;/demo1&quot;)</span><br><span class="line">public class servletDemo1 implements Servlet &#123;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void init(ServletConfig servletConfig) throws ServletException &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException &#123;</span><br><span class="line">        System.out.println(&quot;123&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public ServletConfig getServletConfig() &#123;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public String getServletInfo() &#123;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void destroy() &#123;</span><br><span class="line">        System.out.println(21);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Api"><a href="#Api" class="headerlink" title="Api"></a>Api</h3><h4 id="init"><a href="#init" class="headerlink" title="init"></a>init</h4><ul>
<li>调用时机：默认情况下Servlet第一访问的时候创建Servlet对象，实例化后被调用</li>
<li>调用次数：1次</li>
</ul>
<h4 id="service"><a href="#service" class="headerlink" title="service"></a>service</h4><ul>
<li>调用时机：Servlet每一次被访问的时候</li>
<li>调用次数：多次</li>
</ul>
<h4 id="destroy"><a href="#destroy" class="headerlink" title="destroy"></a>destroy</h4><ul>
<li>调用时机：内存释放或者服务器关闭时，Servlet对象会销毁</li>
<li>调用次数：1次</li>
</ul>
<h3 id="WebServlet注解配置规则"><a href="#WebServlet注解配置规则" class="headerlink" title="WebServlet注解配置规则"></a>WebServlet注解配置规则</h3><p><code>@WebServlet(urlPatterns = &quot;/demo2&quot;, loadOnStartup = 1)</code></p>
<p>urlPatterns &#x3D; xx， xx为路由地址，参数只有urlPatterns时可以省略只写<code>@WebServlet(&quot;xxx&quot;)</code></p>
<ul>
<li>1、数组，可以放多个接口</li>
<li>2、精确匹配：<code>/api/demo</code></li>
<li>3、目录匹配：<code>/api/demo/*</code></li>
<li>4、拓展名匹配：<code>.do</code></li>
<li>5、任意匹配：<code>/</code> 或者 <code>/*</code></li>
</ul>
<p>loadOnStartup为-1表示第一次访问的时候初始化，为正整数或者为0表示Servlet对象创建的时候就调用</p>
<h3 id="HttpServlet"><a href="#HttpServlet" class="headerlink" title="HttpServlet"></a>HttpServlet</h3><p>HttpServlet是对Http协议进行封装的Servlet实现类</p>
<p>需要重写doGet和doPost方法</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">public class ServletDemo_HttpServlet extends HttpServlet &#123;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException &#123;</span><br><span class="line">        super.doGet(req, resp);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException &#123;</span><br><span class="line">        super.doPost(req, resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>封装的原理就是通过<code>ServletRequest</code>强制转为子类<code>HttpServletRequest</code>，在调用<code>getMethod()</code>方法获取调用方法，若是get方法就调用<code>doGet()</code>，post方法就调用<code>doPost()</code></p>
<h3 id="HttpServletRequest"><a href="#HttpServletRequest" class="headerlink" title="HttpServletRequest"></a>HttpServletRequest</h3><h4 id="请求行"><a href="#请求行" class="headerlink" title="请求行"></a>请求行</h4><ul>
<li>请求方法：post&#x2F;get &#x3D;&gt; <code>req.getMethod()</code></li>
<li>访问访问路径：&#x2F;api &#x3D;&gt; <code>req.getContextPath()</code></li>
<li>统一资源定位符：<a target="_blank" rel="noopener" href="http://localhost:8080/api/demo5">http://localhost:8080/api/demo5</a> &#x3D;&gt; <code>req.getRequestURL()</code></li>
<li>统一资源标识符：&#x2F;api&#x2F;demo5 &#x3D;&gt; <code>req.getRequestURI()</code></li>
</ul>
<h4 id="请求参数"><a href="#请求参数" class="headerlink" title="请求参数"></a>请求参数</h4><p><code>req.getQueryString()</code></p>
<h4 id="请求头"><a href="#请求头" class="headerlink" title="请求头"></a>请求头</h4><p><code>req.getHeader(&quot;xxx&quot;)</code></p>
<h4 id="通用获取参数方法"><a href="#通用获取参数方法" class="headerlink" title="通用获取参数方法"></a>通用获取参数方法</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">// 若参数// 请求获得参数的通用方法, 键值对方法，底层用了getQueryString方法</span><br><span class="line">Map&lt;String, String[]&gt; map = req.getParameterMap();</span><br><span class="line">for(String s: map.keySet())&#123;</span><br><span class="line">    System.out.print(s + &quot;:&quot;);</span><br><span class="line">    for(String j: map.get(s))&#123;</span><br><span class="line">        System.out.print(j + &quot;&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(&quot;&quot;);</span><br><span class="line">&#125;</span><br><span class="line">// 若参数有多个，根据key获取参数值，数组</span><br><span class="line">String[] sz = req.getParameterValues(&quot;username&quot;);</span><br><span class="line">// 若参数只有一个，根据key获取值</span><br><span class="line">String sd = req.getParameter(&quot;password&quot;);</span><br></pre></td></tr></table></figure>

<h4 id="乱码问题"><a href="#乱码问题" class="headerlink" title="乱码问题"></a>乱码问题</h4><p>get乱码问题：tomcat进行url解码的默认字符集为ISO-8859-1</p>
<p>解决：1、对乱码进行解码，转为字节数组。2、解码</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">byte ss[] = reqUsername.getBytes(StandardCharsets.ISO_8859_1);</span><br><span class="line">String endUsername = new String(ss, &quot;utf-8&quot;);</span><br></pre></td></tr></table></figure>

<p>post乱码问题解决：<code>req.setCharacterEncoding(&quot;UTF-8&quot;);</code></p>
<h4 id="资源转发"><a href="#资源转发" class="headerlink" title="资源转发"></a>资源转发</h4><p>特点：1、浏览地址栏不变化；2、只能转发当前服务器内部资源；3、一次请求，转发资源间数据共享</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">req.setAttribute(&quot;msg&quot;, &quot;hello&quot;);</span><br><span class="line">req.getAttribute(&quot;msg&quot;);</span><br><span class="line">req.removeAttribute(&quot;msg&quot;);</span><br></pre></td></tr></table></figure>

<p>请求转发：<code>req.getRequestDispatcher(&quot;/demo&quot;).forward(req, resp);</code></p>
<h3 id="HttpServletResponse"><a href="#HttpServletResponse" class="headerlink" title="HttpServletResponse"></a>HttpServletResponse</h3><h4 id="重定向"><a href="#重定向" class="headerlink" title="重定向"></a><strong>重定向</strong></h4><p>特点：1、路由器地址栏发送变化；2、可以重定向任意位置（服务器内部或者外部都可以）；3、两次请求，不能在多个资源中使用request共享数据</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">// 方法一</span><br><span class="line">// 设置状态码</span><br><span class="line">response.setStatus(302);</span><br><span class="line">//  设置响应头</span><br><span class="line">response.setHeader(&quot;Location&quot;, &quot;/servlet_demo/demo1&quot;);</span><br><span class="line"></span><br><span class="line">// 方法二</span><br><span class="line">// 重定向简化写法</span><br><span class="line">// request.getContextPath()：获取虚拟目录</span><br><span class="line">response.sendRedirect(request.getContextPath() + &quot;/demo1&quot;);</span><br></pre></td></tr></table></figure>

<h4 id="response响应数据"><a href="#response响应数据" class="headerlink" title="response响应数据"></a>response响应数据</h4><h5 id="字符输入流"><a href="#字符输入流" class="headerlink" title="字符输入流"></a>字符输入流</h5><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">// 设置请求头编码为utf-8并且支持html格式</span><br><span class="line">response.setHeader(&quot;content-type&quot;, &quot;text/html;charset=utf-8&quot;);</span><br><span class="line">//  获得字符输入流</span><br><span class="line">PrintWriter printWriter = response.getWriter();</span><br><span class="line">printWriter.write(&quot;&lt;h1&gt;你好&lt;/h1&gt;&quot;);</span><br></pre></td></tr></table></figure>

<h5 id="字节输入流"><a href="#字节输入流" class="headerlink" title="字节输入流"></a>字节输入流</h5><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">FileInputStream file = new FileInputStream(&quot;C:\\Users\\lenovo\\Pictures\\Saved Pictures\\qq.jpg&quot;);</span><br><span class="line">ServletOutputStream servletOutputStream = response.getOutputStream();</span><br><span class="line">byte[] b = new byte[1024];</span><br><span class="line">int len = 0;</span><br><span class="line">while((len = file.read(b)) != -1)&#123;</span><br><span class="line">    servletOutputStream.write(b, 0, len);</span><br><span class="line">&#125;</span><br><span class="line">file.close(); // 这里需要关闭资源</span><br></pre></td></tr></table></figure>

<h5 id="JSON格式"><a href="#JSON格式" class="headerlink" title="JSON格式"></a>JSON格式</h5><p>需要导入fastjson包</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">      &lt;groupId&gt;com.alibaba&lt;/groupId&gt;</span><br><span class="line">      &lt;artifactId&gt;fastjson&lt;/artifactId&gt;</span><br><span class="line">      &lt;version&gt;1.2.62&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<p>例子</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">int n[] = &#123;1,2,3,6,4,5&#125;;</span><br><span class="line">String j = JSON.toJSONString(n);</span><br><span class="line">response.setContentType(&quot;text/html;charset=utf-8&quot;);</span><br><span class="line">response.getWriter().write(j);</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="http://www.lijunxi.site">Jixer</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="http://www.lijunxi.site/posts/2996697887/">http://www.lijunxi.site/posts/2996697887/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://www.lijunxi.site" target="_blank">Jixer的小屋</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"><div class="social-share" data-image="https://q1.qlogo.cn/g?b=qq&amp;nk=2770063826&amp;s=640" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="/pluginsSrc/butterfly-extsrc/sharejs/dist/css/share.min.css?v=1.1.3" media="print" onload="this.media='all'"><script src="/pluginsSrc/butterfly-extsrc/sharejs/dist/js/social-share.min.js?v=1.1.3" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/3590194591/" title="数据库系统原理错题集"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">数据库系统原理错题集</div></div></a></div><div class="next-post pull-right"><a href="/posts/669583838/" title="Java错题集"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Java错题集</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/669583838/" title="Java错题集"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-01-17</div><div class="title">Java错题集</div></div></a></div><div><a href="/posts/3692994522/" title="Java面试题基础(下)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-02-26</div><div class="title">Java面试题基础(下)</div></div></a></div><div><a href="/posts/3305483931/" title="Java面试题基础(上)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-02-24</div><div class="title">Java面试题基础(上)</div></div></a></div><div><a href="/posts/3771679189/" title="JVM虚拟机基础篇"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-04-07</div><div class="title">JVM虚拟机基础篇</div></div></a></div><div><a href="/posts/532684030/" title="Java面试题基础(中)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-02-25</div><div class="title">Java面试题基础(中)</div></div></a></div><div><a href="/posts/1952430746/" title="Java面试题并发(上)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-03-13</div><div class="title">Java面试题并发(上)</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="" data-original="https://q1.qlogo.cn/g?b=qq&amp;nk=2770063826&amp;s=640" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Jixer</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">52</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">19</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/2770063826"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content"></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#JDBC"><span class="toc-text">JDBC</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B"><span class="toc-text">快速上手</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#API"><span class="toc-text">API</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#DriverManager"><span class="toc-text">DriverManager</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Connection"><span class="toc-text">Connection</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Statement"><span class="toc-text">Statement</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#PreparedStatement"><span class="toc-text">PreparedStatement</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ResultSet"><span class="toc-text">ResultSet</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Druid"><span class="toc-text">Druid</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Mybaits"><span class="toc-text">Mybaits</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%AE%E5%BD%95"><span class="toc-text">目录</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#mybatis-config%E7%9A%84%E9%85%8D%E7%BD%AE"><span class="toc-text">mybatis-config的配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#XXXMapper%E7%9A%84%E9%85%8D%E7%BD%AE"><span class="toc-text">XXXMapper的配置</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#select%E6%A0%87%E7%AD%BE"><span class="toc-text">select标签</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#insert%E6%A0%87%E7%AD%BE"><span class="toc-text">insert标签</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#updated%E6%A0%87%E7%AD%BE"><span class="toc-text">updated标签</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#delete%E6%A0%87%E7%AD%BE"><span class="toc-text">delete标签</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E8%A7%A3%E6%96%B9%E5%BC%8F"><span class="toc-text">注解方式</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Servlet"><span class="toc-text">Servlet</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8"><span class="toc-text">快速入门</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Api"><span class="toc-text">Api</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#init"><span class="toc-text">init</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#service"><span class="toc-text">service</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#destroy"><span class="toc-text">destroy</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#WebServlet%E6%B3%A8%E8%A7%A3%E9%85%8D%E7%BD%AE%E8%A7%84%E5%88%99"><span class="toc-text">WebServlet注解配置规则</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#HttpServlet"><span class="toc-text">HttpServlet</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#HttpServletRequest"><span class="toc-text">HttpServletRequest</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E8%A1%8C"><span class="toc-text">请求行</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E5%8F%82%E6%95%B0"><span class="toc-text">请求参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E5%A4%B4"><span class="toc-text">请求头</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%80%9A%E7%94%A8%E8%8E%B7%E5%8F%96%E5%8F%82%E6%95%B0%E6%96%B9%E6%B3%95"><span class="toc-text">通用获取参数方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B9%B1%E7%A0%81%E9%97%AE%E9%A2%98"><span class="toc-text">乱码问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%B5%84%E6%BA%90%E8%BD%AC%E5%8F%91"><span class="toc-text">资源转发</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#HttpServletResponse"><span class="toc-text">HttpServletResponse</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%87%8D%E5%AE%9A%E5%90%91"><span class="toc-text">重定向</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#response%E5%93%8D%E5%BA%94%E6%95%B0%E6%8D%AE"><span class="toc-text">response响应数据</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E8%BE%93%E5%85%A5%E6%B5%81"><span class="toc-text">字符输入流</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%AD%97%E8%8A%82%E8%BE%93%E5%85%A5%E6%B5%81"><span class="toc-text">字节输入流</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#JSON%E6%A0%BC%E5%BC%8F"><span class="toc-text">JSON格式</span></a></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/2029624507/" title="2022年算法队选拔赛">2022年算法队选拔赛</a><time datetime="2024-05-09T15:00:27.000Z" title="发表于 2024-05-09 23:00:27">2024-05-09</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/1978524057/" title="牛客小白月赛84">牛客小白月赛84</a><time datetime="2024-05-08T14:40:35.000Z" title="发表于 2024-05-08 22:40:35">2024-05-08</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/131339317/" title="软件测试资料">软件测试资料</a><time datetime="2024-05-07T03:12:52.000Z" title="发表于 2024-05-07 11:12:52">2024-05-07</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/2394234105/" title="第十四届蓝桥杯B组国赛">第十四届蓝桥杯B组国赛</a><time datetime="2024-05-05T13:40:15.000Z" title="发表于 2024-05-05 21:40:15">2024-05-05</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/1405472621/" title="Leetcode第396场周赛">Leetcode第396场周赛</a><time datetime="2024-05-05T03:58:25.000Z" title="发表于 2024-05-05 11:58:25">2024-05-05</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2024 By Jixer</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://beian.miit.gov.cn/#/Integrated/index" style="color:white" target="_blank">蜀ICP备2022009955号-1</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js?v=4.13.0"></script><script src="/js/main.js?v=4.13.0"></script><script src="/pluginsSrc/@fancyapps/ui/dist/fancybox/fancybox.umd.js?v=5.0.33"></script><div class="js-pjax"></div><script src="/js/custom-fancybox-umd-min.js"></script><script src="/js/custom-busuanzi-pure-mini.js"></script><script src="/js/Valine.min.js"></script><script src="/js/custom-social-share.min.js"></script><script src="/js/custom-typed-umd-min.js"></script><script src="/js/av-min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js?v=4.13.0"></script></div></div>
        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body></html>